package com.example.indenture.util;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;

/**
 * 基于加盐算法实现的加密解密的实现
 *
 * @author CY
 * @date 2023/03/15 17:03
 **/
public class PasswordUtil {
    public static String encrypt(String password) {
        //参数校验
        if (password == null || !StringUtils.hasLength(password)) {
            return null;
        }
        //加盐算法的实现
        String salt = UUID.randomUUID().toString().replace("-", "");
        String finalPassword = DigestUtils.md5DigestAsHex((salt + password).getBytes());
        return salt + finalPassword;
    }

    public static boolean decrypt(String password, String finalPassword) {
        if (!StringUtils.hasLength(password) || !StringUtils.hasLength(finalPassword)) {
            return false;
        }
        if (finalPassword.length() < 64) {
            return false;
        }
        String salt = finalPassword.substring(0, 32);
        String securityPassword = DigestUtils.md5DigestAsHex((salt + password).getBytes());
        return finalPassword.equals(salt + securityPassword);
    }
}
